package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import org.apache.commons.fileupload.FileItem;
import service.StoreService;
import util.RequestFileDispatcher;

import top.ConfigCenter;

@WebServlet(name = "StoreServlet", urlPatterns = "*.store")
public class StoreServlet extends HttpServlet {

    private static final StoreService storeService = ConfigCenter.getStoreService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求字符集
        req.setCharacterEncoding("UTF-8");

        switch(req.getServletPath()) {
            case "/register.store": {
                try {
                    //使用帮助类从浏览器接收表单数据（包括文件和非文件数据）
                    RequestFileDispatcher data = new RequestFileDispatcher(req);
                    //根据表单控件name属性，获取对应的非文件数据：getParam
                    Long uid     = Long.parseLong(data.getParam("userid"));
                    String pass  = data.getParam("password");
                    String name  = data.getParam("storename");
                    //根据表单控件name属性，获取对应的文件数据：getFileItem
                    FileItem pic = data.getFileItem("storepic");

                    if(storeService.openNewStore(uid, pass, name, pic, req.getServletContext().getRealPath(ConfigCenter.STOREPICHOME).replace('\\', '/')) != null) resp.sendRedirect("mystore.jsp");
                    else {
                        req.getSession().setAttribute("OESErrorCode", "OPENSTOREFAIL");
                        resp.sendRedirect(req.getContextPath() + "/error.jsp");
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
            }

            case "/get.store": {

            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
